#!/usr/bin/env python3
# DATA: 2024/10/20
# author: 曹文耀
#


import logging
import uuid

from sqlalchemy import and_
from sqlalchemy.orm import Session

from src.common.dbase import models


async def operate_topic(db: Session, data: dict):
    if data.get('_id'):
        pass
    else:
        uid = uuid.uuid1().hex
        data.update({"_id": uid})
        try:
            initem = models.TopicInfo(**data)
            db.add(initem)
            db.commit()
            return uid
        except Exception as e:
            logging.error(f"往topic表插入数据的时候出错了：{e}")
            return False


async def sel_topic(db: Session, conds: dict):
    if conds:
        cond = []
        if conds.get('cutwd'):
            cond.append(models.TopicInfo.cutwd.like(f'%{conds["cutwd"]}%'))
        return db.query(models.TopicInfo).filter(and_(cod for cod in cond)).order_by(
            models.TopicInfo.uptime.desc()).limit(1000).all()
    else:
        return db.query(models.TopicInfo).order_by(models.TopicInfo.uptime.desc()).limit(1000).all()
